#!/bin/bash
# Author: hukey

# 检查系统版本
function Check_linux_system(){
  linux_version=`cat /etc/redhat-release`
  if [[ ${linux_version} =~ "CentOS Linux release 7" ]];then
    echo -e "\033[32;1m 系统为 ${linux_version} \033[0m \n"
  else
    echo -e "\033[31;1m 系统不是CentOS,该脚本只支持CentOS环境\033[0m \n"
    exit 1
  fi
}

# 检测iso文件是否存在
function Check_iso(){
  if [ ! -f ./iso/*.iso ];then
    echo -e "\033[31;1m 未检测到 ISO 镜像文件的存在，请自行下载ISO文件并放置到 iso 目录下！\033[0m"
  else
    ISONAME=$(ls ./iso/*.iso| awk -F '/' '{print $NF}')
    echo -e "\033[32;1mISO文件名：${ISONAME}\033[0m"
    mkdir -p ./iso/centos/
  fi
}
# 检查网络
function Check_network(){
  ping -w 1 -c 1 mirrors.aliyun.com &> /dev/null
  if [ $? -eq 0 ];then
    echo -e "\033[32;1m 网络连接正常.\033[0m"
  else
    echo -e "\033[31;m 无法连接到公网，请网络或者DNS配置.\033[0m"
    exit 1
  fi
}

# 初始化 yum 源
function Init_system(){
  mkdir /etc/yum.repos.d/bak
  mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak/
  curl -s http://mirrors.aliyun.com/repo/Centos-7.repo -o /etc/yum.repos.d/Centos-7.repo
  sed -i '/aliyuncs/d' /etc/yum.repos.d/Centos-7.repo
}

# 安装并配置DHCP
function Dhcp_deploy(){
  yum install net-tools dhcp -y
  IP=$(ifconfig | egrep cast | awk '{print $2}')
  NETMASK=$(ifconfig | egrep cast | awk '{print $4}')
  IP_CIDR=$(echo ${IP} | awk -F '.' '{$NF=0}{print $1"."$2"."$3"."$4}')
  GATEWAY=$(ip route show  | awk '/default via/{print $3}')
cat << EOF > /etc/dhcp/dhcpd.conf 
subnet $IP_CIDR netmask $NETMASK {
range $IP $GATEWAY;
option domain-name-servers $GATEWAY;
option routers $GATEWAY;
default-lease-time 600;
max-lease-time 7200;
next-server $IP;
filename "pxelinux.0";
}
EOF
systemctl start dhcpd ; systemctl enable dhcpd
}

# 安装并配置 tftp
function Tftp_deploy(){
  yum install tftp-server syslinux -y 
  mount ./iso/$ISONAME ./iso/centos/
  cp -a ./iso/centos/isolinux/boot.msg /var/lib/tftpboot/
  cp -a ./iso/centos/images/pxeboot/{initrd.img,vmlinuz} /var/lib/tftpboot/
  cp -a /usr/share/syslinux/pxelinux.0 /var/lib/tftpboot/
  mkdir -p /var/lib/tftpboot/pxelinux.cfg/
  cp -a ./config/default /var/lib/tftpboot/pxelinux.cfg/
  sed -i "s@1.1.1.1@${IP}@g" /var/lib/tftpboot/pxelinux.cfg/default
  umount ./iso/centos/
  systemctl start tftp ; systemctl enable tftp
}

# 安装并配置 http
function Http_deploy(){
  yum install httpd -y
  mkdir -p /var/www/html/centos/
  mount ./iso/$ISONAME /var/www/html/centos/
  cp -a ./config/ks.cfg  /var/www/html/
  sed -i "s@1.1.1.1@${IP}@g" /var/www/html/ks.cfg
  systemctl start httpd ; systemctl enable httpd
}

Check_linux_system
Check_network
Check_iso
Init_system
Dhcp_deploy
Tftp_deploy
Http_deploy
echo -e "\033[32;1m == KickStart 配置完成！==\033[0m"
echo -e "\033[32;1m [如有任何问题请联系作者 E-mail: mickey.20@qq.com]\033[0m"
